package com.hm.manage.pach;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.hm.manage.domain.Xxxtsimp;
import com.hm.manage.mapper.XxxtsimpMapper;
import com.hm.manage.service.IXxxtsimpService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigInteger;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;
import java.util.Locale;

@Slf4j
@Component
public class FormatJson {

    @Autowired
    private PostExample postExample;

    @Autowired
    private IXxxtsimpService ixxxtsimpService;

    @Autowired
    private GetExample getExample;


    /**
     * 处理清单
     * @param list
     * @return
     */
    public BigInteger formatJson(String list) {

        JSONObject root = JSONObject.parseObject(list);
        log.info("--------开始解析数据----------");
        // 获取到分页信息
        JSONObject data = root.getJSONObject("data");
        String regionCode = root.getString("regionCode");
        BigInteger pageNum = data.getBigInteger("pageNum");
        BigInteger pageSize = data.getBigInteger("pageSize");
        BigInteger total = data.getBigInteger("total");
        BigInteger pages = data.getBigInteger("pages");

        log.info("--------分页信息----------");
        log.info("---pageNum:{}---pageSize:{}----total:{}---pages:{}------",pageNum,pageSize,total,pages);

        // 获取详细数据
        JSONArray jsonArray = data.getJSONArray("list");
        log.info("--------列表信息----------");
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            String systemName = jsonObject.getString("systemName");
            String orgName = jsonObject.getString("orgName");
            String orgCode = jsonObject.getString("orgCode");
            String archiveCode = jsonObject.getString("archiveCode");
            String locationAddress = jsonObject.getString("locationAddress");
            String createTime = jsonObject.getString("createTime");
            String approvalReason = jsonObject.getString("approvalReason");

            String cz = "";
            log.info("-------systemName:{}------orgName:{}------archiveCode:{}----",systemName,orgName,archiveCode);

            // 开始入库
            // 1 构造实体
            Xxxtsimp xxxtsimp = new Xxxtsimp();
            xxxtsimp.setCreateTime(new Date());
            xxxtsimp.setCcjsj(new Date());
            xxxtsimp.setXtmc(systemName);
            xxxtsimp.setDwmc(orgName);
            xxxtsimp.setSzdz(locationAddress);
            xxxtsimp.setArchiveCode(archiveCode);
            xxxtsimp.setCjsj(createTime);
            if (approvalReason == null) {
                cz = "审核";
            }else if (approvalReason.equals("审核通过")) {
                cz = "辖区调整";
            }else if (approvalReason.equals("重复提交或错误提交")) {
                cz = "";
            }
            xxxtsimp.setCz(cz);
            xxxtsimp.setApprovalReason(approvalReason);
            xxxtsimp.setOrgCode(orgCode);
            xxxtsimp.setSzqy(regionCode);
            // 2 写入
            ixxxtsimpService.save(xxxtsimp);
        }
        return pages;
    }


    /**
     * 单个处理系统备案信息并插入
     */
    public void handleXtbaxxAndInsert(String archiveCode) {
        // 先调用接口获取到数据并解析出来
        String json = getExample.getCtbaxq(archiveCode);
        // 先判断数据，没数据就不干了
        JSONObject root = JSONObject.parseObject(json);
        if (!root.getString("msg").equals("操作成功") || root.getJSONObject("data") == null) {
            log.error("--------{}请求的数据为空---------",archiveCode);
            return;
        }
        // 开始拿数据咯
        JSONObject data = root.getJSONObject("data");
        String recordCode = data.getString("recordCode")==null?"":data.getString("recordCode");// 备案编号
        String systemName = data.getString("systemName")==null?"":data.getString("systemName");// 系统名称
        String orgName = data.getString("orgName")==null?"":data.getString("orgName");// 单位编码
        String socialCreditCode = data.getString("socialCreditCode")==null?"":data.getString("socialCreditCode");// 统一社会信用代码
        String locationAddress = data.getString("locationAddress")==null?"":data.getString("locationAddress");// 系统所在地址
        String subDistrict = data.getString("subDistrict")==null?"":data.getString("subDistrict");// 街道/乡镇
        String affiliatedUnitCode = data.getString("affiliatedUnitCode")==null?"":data.getString("affiliatedUnitCode"); // 派出所编码
        String affiliatedUnitName = data.getString("affiliatedUnitName")==null?"":data.getString("affiliatedUnitName"); // 派出所名称
        String publicDeviceCount = data.getString("publicDeviceCount")==null?"":data.getString("publicDeviceCount"); // 公共安全区域图像采集设备数量
        String leaderName = data.getString("leaderName")==null?"":data.getString("leaderName"); // 安全负责人姓名
        String leaderTelephone = data.getString("leaderTelephone")==null?"":data.getString("leaderTelephone"); // 安全负责人手机号
        String transactor = data.getString("transactor")==null?"":data.getString("transactor"); // 经办人姓名
        String transactorId = data.getString("transactorId")==null?"":data.getString("transactorId"); // 经办人身份证号码
        String pointInfo = data.getString("pointInfo")==null?"":data.getString("pointInfo"); // 附件
        JSONArray provinceCode = data.getJSONArray("placeType");
        String pvalueName = "";
        for (int i = 0; i < provinceCode.size(); i++) {
            JSONObject province = provinceCode.getJSONObject(i);
            pvalueName = pvalueName+province.getString("valueName");
        }
        String svalueName = "";
        JSONArray jsonArray = data.getJSONArray("subPlaceType");
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject subPlaceType = jsonArray.getJSONObject(i);
            svalueName = svalueName+subPlaceType.getString("valueName");
        }


        //更新数据到数据库
        Xxxtsimp xxxtsimp = new Xxxtsimp();
        xxxtsimp.setArchiveCode(archiveCode);
        List<Xxxtsimp> xxxtsimps = ixxxtsimpService.selectXxxtsimpList(xxxtsimp);
        for (Xxxtsimp xxxtsimp1 : xxxtsimps) {
            xxxtsimp1.setSocialCreditCode(socialCreditCode);
            xxxtsimp1.setLocationAddress(locationAddress);
            xxxtsimp1.setSubDistrict(subDistrict);
            xxxtsimp1.setAffiliatedUnitCode(affiliatedUnitCode);
            xxxtsimp1.setAffiliatedUnitName(affiliatedUnitName);
            xxxtsimp1.setPublicDeviceCount(publicDeviceCount);
            xxxtsimp1.setLeaderName(leaderName);
            xxxtsimp1.setLeaderTelephone(leaderTelephone);
            xxxtsimp1.setPointInfo(pointInfo);
            xxxtsimp1.setTransactor(transactor);
            xxxtsimp1.setTransactorId(transactorId);
            xxxtsimp1.setBabh(recordCode);
            xxxtsimp1.setPlaceType(pvalueName);
            xxxtsimp1.setSubPlaceType(svalueName);
            // 更新数据
            ixxxtsimpService.updateXxxtsimp(xxxtsimp1);
        }
    }
    /**
     * 全量处理系统备案信息并插入
     */
    public void HandleAllXtbaxxAndInsert(){
        // 先遍历所有的列表数据
        Xxxtsimp xxxtsimp1 = new Xxxtsimp();
        LocalDate today = LocalDate.now();
        Date date = Date.from(today.atStartOfDay(ZoneId.systemDefault()).toInstant());

        xxxtsimp1.setCcjsj(date);
        List<Xxxtsimp> list = ixxxtsimpService.selectXxxtsimpList(xxxtsimp1);
        int i = 1;
        int all = list.size();
        for (Xxxtsimp xxxtsimp : list) {
            log.info("-----------执行次数{}/{}--------------",i,all);
            if (xxxtsimp.getPlaceType() == null || xxxtsimp.getSubPlaceType() == null) {
                handleXtbaxxAndInsert(xxxtsimp.getArchiveCode());
            }

            i++;
        }
    }

    /***
     * 处理单位详情的三个图片
     */
    public void handleOrgDetail(String orgCode){
        // 先调用接口获取到数据并解析出来
        String json = getExample.getPics(orgCode);
        // 先判断数据，没数据就不干了
        JSONObject root = JSONObject.parseObject(json);
        if (!root.getString("msg").equals("操作成功") || root.getJSONObject("data") == null) {
            log.error("--------handleOrgDetail{}请求的数据为空---------",orgCode);
            return;
        }
        JSONObject data = root.getJSONObject("data");
        JSONArray orgMgtAttachmentList = data.getJSONArray("orgMgtAttachmentList");
        String sqs = "";
        String yyzz = "";
        String frdjzs = "";
        for (int i = 0; i < orgMgtAttachmentList.size(); i++) {
            JSONObject orgMgtAttachment = orgMgtAttachmentList.getJSONObject(i);
            String attachmentType = orgMgtAttachment.getString("attachmentType");
            String attachmentUrl = orgMgtAttachment.getString("attachmentUrl");
            //log.info("-序列：{}------attachmentType：{}------attachmentUrl：{}",i,attachmentType,attachmentUrl);
            if (attachmentType.equals("authorizationLetter")) { //委托办理备案登记授权书加盖公章authorizationLetter  sqs
                sqs = attachmentUrl;
            } else if (attachmentType.equals("businessLicense")) { //营业执照businessLicense  yyzz
                yyzz = attachmentUrl;
            } else if (attachmentType.equals("legalCertificate")) { //法人登记证书复印件加盖公章legalCertificate  frdjzs
                frdjzs = attachmentUrl;
            }
        }
        //log.info();
        // 获取对象
        Xxxtsimp xxxtsimp = new Xxxtsimp();
        xxxtsimp.setOrgCode(orgCode);
        List<Xxxtsimp> xxxtsimps = ixxxtsimpService.selectXxxtsimpList(xxxtsimp);
        for (Xxxtsimp xxxtsimp1 : xxxtsimps) {
            xxxtsimp1.setSqs(sqs);
            xxxtsimp1.setYyzz(yyzz);
            xxxtsimp1.setFrdjzs(frdjzs);
            ixxxtsimpService.updateXxxtsimp(xxxtsimp1);
        }

    }

    public void handleAllOrgDetail(){
        // 先遍历所有的列表数据
        Xxxtsimp xxxtsimp1 = new Xxxtsimp();
        LocalDate today = LocalDate.now();
        Date date = Date.from(today.atStartOfDay(ZoneId.systemDefault()).toInstant());

        xxxtsimp1.setCcjsj(date);
        List<Xxxtsimp> list = ixxxtsimpService.selectXxxtsimpList(xxxtsimp1);
        for (int i = 0; i < list.size(); i++) {
            log.info("-----执行的次数：{}/{}----------",i+1,list.size());
            handleOrgDetail(list.get(i).getOrgCode());
        }
    }


}
